<?php
namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Loader;
use think\Page;
use think\Validate;
use \app\admin\model\CaringTask;
use \app\admin\model\Staff;
use \app\admin\model\TrainingTasks;
use \app\admin\model\Volunteer as Volunteers;
use \app\admin\model\VolunteerAudit;

class Volunteer extends Api
{
    protected $noNeedLogin      = [];
    protected $noNeedRight      = '*';
    protected $user_id          = 0;
    protected $volunteer_info   = null;
    protected $vmodel           = null;
    protected $cmodel           = null;
    protected $tmodel           = null;
    protected $noCheckVolunteer = ['applyinfo', 'apply'];

    public function _initialize()
    {
        parent::_initialize();
        $this->user_id = $this->auth->id;
        $this->vmodel  = new Volunteers;
        $this->cmodel  = new CaringTask;
        $this->tmodel  = new TrainingTasks;

        $this->volunteer_info = $this->vmodel
            ->where(['user_id' => $this->auth->id])
            ->find();

        $actionname = strtolower($this->request->action());

        // 不需要檢查義工的接口
        if (! in_array($actionname, $this->noCheckVolunteer) && ! $this->volunteer_info) {
            $this->error('請加入義工', [], 202);
        }
    }

    //獲取最新申請記錄信息

    public function getNew()
    {
        $info     = [];
        $info_buf = [];

        $vamodel = new VolunteerAudit;

        $info = $vamodel
            ->field('*')
            ->where(['user_id' => $this->auth->id])
            ->order('id desc')
            ->find();

        $this->success('請求成功', $info);
    }
    /**
     * @MethodName 加入關懷圈
     * @Author     Allen
     * @DateTime   2021-10-05T17:12:04+0800
     * @param      string
     * @return     [type]
     */
    public function apply($value = '')
    {
        $rq_data = $this->request->param();
        $vamodel = new VolunteerAudit;
// 		if ($this->volunteer_info&&$this->volunteer_info['affiliated_center_id']==$rq_data['affiliated_center_id']) {
        // 			$this->error('您已申請義工,請勿重複提交申請');
        // 		}
        // 義工審核狀態0、未成為義工,1待審核2通過3拒絕
        $volunteer_audit_status = 0;

        $volunteer_audit = $vamodel
            ->where(['user_id' => $this->auth->id])
            ->order('id desc')
            ->find();
        if ($volunteer_audit && $volunteer_audit['affiliated_center_id'] == $rq_data['affiliated_center_id']) {
            switch ($volunteer_audit['status']) {
                case '1':
                    $this->error('請耐心等待審核');
                    break;
                case '2':
                 $this->error('審核已通過,請勿重複提交申請');
                    break;
            }
        }

        $validate = Loader::validate('VolunteerAudit');
        if (! $validate->scene('apply')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $insert_arr            = [];
        $insert_arr['user_id'] = $this->user_id;
        //$insert_arr['area_one_id'] = $rq_data['area_one_id'];
        $insert_arr['area_tow_id']   = $rq_data['area_tow_id'];
        $insert_arr['name']          = $rq_data['name'];
        $insert_arr['id_card']       = $rq_data['id_card'];
        $insert_arr['id_card_front'] = isset($rq_data['id_card_front']) ? $rq_data['id_card_front'] : '';
        $insert_arr['id_card_after'] = isset($rq_data['id_card_after']) ? $rq_data['id_card_after'] : '';
        $insert_arr['birthday']      = $rq_data['birthday'];
        // $insert_arr['id_card_positive_images'] = $rq_data['id_card_positive_images'];
        // $insert_arr['id_card_back_images'] = $rq_data['id_card_back_images'];
        $insert_arr['mobile']       = $rq_data['mobile'];
        $insert_arr['mobile_china'] = $rq_data['mobile_china'];
        $insert_arr['remark']       = $rq_data['remark'];
        $insert_arr['wechat_id']    = $rq_data['wechat_id'];
        if ($rq_data['other'] != '') {
            $service_type = $rq_data['service_type'] . ':' . $rq_data['other'];
        } else {
            $service_type = $rq_data['service_type'];
        }
        $insert_arr['service_type']         = $service_type;
        $insert_arr['province']             = $rq_data['province'];
        $insert_arr['city']                 = $rq_data['city'];
        $insert_arr['district']             = isset($rq_data['district']) ? $rq_data['district'] : '';
        $insert_arr['address']              = $rq_data['address'];
        $insert_arr['emergency_contact']    = isset($rq_data['emergency_contact']) ? $rq_data['emergency_contact'] : '';
        $insert_arr['email']                = isset($rq_data['email']) ? $rq_data['email'] : '';
        $insert_arr['affiliated_center_id'] = isset($rq_data['affiliated_center_id']) ? $rq_data['affiliated_center_id'] : '';
        if ($volunteer_audit && $volunteer_audit['affiliated_center_id'] == $rq_data['affiliated_center_id']) {

            $insert_arr['audittime']  = 0;
            $insert_arr['audreason']  = '';
            $insert_arr['updatetime'] = time();
            $insert_arr['status']     = '1';
            $insert_arr['is_read']    = '1';
            $status                   = $vamodel
                ->where(['id' => $volunteer_audit['id']])
                ->update($insert_arr);
        } else {
            $insert_arr['createtime'] = time();
            $status                   = $vamodel->insert($insert_arr);
        }

        if (! $status) {
            $this->error('操作失敗');
        }

        $this->success('操作成功');
    }

    /**
     * @MethodName 獲取申請詳情
     * @Author     Allen
     * @DateTime   2021-10-05T17:20:44+0800
     * @param      string
     */
    public function applyInfo($value = '')
    {

        $info     = [];
        $info_buf = [];
        // 義工審核狀態0、未成為義工,1待審核2通過3拒絕
        $info_buf['status']                  = 0;
        $info_buf['createtime']              = 0;
        $info_buf['audittime']               = 0;
        $info_buf['audreason']               = '';
        $info_buf['area_one_id']             = '';
        $info_buf['area_tow_id']             = '';
        $info_buf['name']                    = '';
        $info_buf['id_card']                 = '';
        $info_buf['id_card_front']           = '';
        $info_buf['id_card_after']           = '';
        $info_buf['birthday']                = '';
        $info_buf['id_card_positive_images'] = '';
        $info_buf['id_card_back_images']     = '';
        $info_buf['mobile']                  = '';
        $info_buf['province']                = '';
        $info_buf['city']                    = '';
        $info_buf['district']                = '';
        $info_buf['address']                 = '';
        $info_buf['email']                   = '';
        $info_buf['emergency_contact']       = '';
        $info_buf['affiliated_center_id']    = 0;
        $info_buf['is_read']                 = 1;

        $info = $info_buf;

        $vamodel = new VolunteerAudit;

        $volunteer_audit = $vamodel
            ->field('status,createtime,audittime,audreason,area_one_id,area_tow_id,name,id_card,id_card_front,id_card_after,birthday,id_card_positive_images,id_card_back_images,mobile,province,city,district,city,district,address,email,emergency_contact,affiliated_center_id,is_read')
            ->where(['user_id' => $this->auth->id])
            ->order('id desc')
            ->find();

        if ($volunteer_audit) {
            $volunteer_audit['audreason'] = $volunteer_audit['audreason'] ? $volunteer_audit['audreason'] : '';
            $info                         = $volunteer_audit;
        }

        if ($this->volunteer_info) {
            $info['status'] = 2;
        }

        if (! $this->volunteer_info && isset($volunteer_audit) && $volunteer_audit['status'] == '2') {
            $info = $info_buf;
        }

        $affiliated_center_name         = db('affiliated_center')->where(['id' => $info['affiliated_center_id']])->value('name');
        $info['affiliated_center_name'] = $affiliated_center_name ? $affiliated_center_name : '';

        $this->success('請求成功', $info);
    }
    /**
     * @MethodName 通过的申请
     * @Author     Allen
     * @DateTime   2021-10-05T17:20:44+0800
     * @param      string
     */
    public function auditList($value = '')
    {

        $vamodel = new VolunteerAudit;

        $list = $vamodel
            ->field('status,createtime,audittime,audreason,area_one_id,area_tow_id,name,id_card,id_card_front,id_card_after,birthday,id_card_positive_images,id_card_back_images,mobile,province,city,district,city,district,address,email,emergency_contact,affiliated_center_id,is_read')
            ->where(['user_id' => $this->auth->id])
            ->where('status', 2)

            ->order('id desc')
            ->select();

        $this->success('請求成功', $list);
    }
    /**
     * [setVolunteerAuditRead 义工审核已读]
     * @param string $value [description]
     */
    public function setVolunteerAuditRead($value = '')
    {
        $vamodel = new VolunteerAudit;
        $status  = $vamodel
            ->where(['user_id' => $this->auth->id])
            ->update(['is_read' => '2']);

        $this->success('操作成功');
    }

    /**
     * @MethodName 獲取員工列表
     * @Author     Allen
     * @DateTime   2021-10-05T22:29:36+0800
     * @param      string
     * @return     [type]
     */
    public function getStaffList($value = '')
    {
        $model       = new Staff;
        $area_tow_id = $this->request->post("area_tow_id", 0);

        $where = ['status' => 'normal'];
        if ($area_tow_id) {
            $where['area_tow_id'] = $area_tow_id;
        }
        $total = $model
            ->where($where)
            ->count();

        $page = new Page($total, 10);
        $list = $model
            ->field('id,avatar,area_one_id,area_tow_id,nickname')
            ->where($where)
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('id desc')
            ->select();

        foreach ($list as $key => &$value) {
            $region_address = db('area')->where(['id' => $value['area_one_id']])->value('name');
            $city           = db('area')->where(['id' => $value['area_tow_id']])->value('name');
            if ($city) {
                $region_address = $region_address . $city;
            }
            $value['region_address'] = $region_address ? $region_address : '';
            unset($value['area_one_id']);
            unset($value['area_tow_id']);
            unset($value['logintime_text']);
        }

        unset($value);
        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];
        $this->success('請求成功', $data);
    }

    /**
     * @MethodName 獲取義工列表
     * @Author     Allen
     * @DateTime   2021-10-05T22:35:51+0800
     * @param      string
     * @return     [type]
     */
    public function getVolunteerList($value = '')
    {
        $area_tow_id = $this->request->post("area_tow_id", 0);

        $where = ['u.status' => 'normal'];
        if ($area_tow_id) {
            $where['v.area_tow_id'] = $area_tow_id;
        }
        $total = $this->vmodel
            ->alias('v')
            ->where($where)
            ->join('user u', 'v.user_id = u.id')
            ->where('v.deletetime', null)
            ->count();

        $page = new Page($total, 10);
        $list = $this->vmodel
            ->alias('v')
            ->field('v.*')
            ->where($where)
            ->where('v.deletetime', null)
            ->join('user u', 'v.user_id = u.id')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('v.id desc')
            ->select();

        foreach ($list as $key => &$value) {

            $value['region_address'] = db('area')
                ->where(['id' => $value['affiliated_center_id']])
                ->value('name');

        }
        unset($value);

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];
        $this->success('請求成功', $data);
    }
    /**
     * @MethodName 獲取義工列表-用户全部义工身份
     * @Author     Allen
     * @DateTime   2021-10-05T22:35:51+0800
     * @param      string
     * @return     [type]
     */
    public function getVolunteerListUser($value = '')
    {
        $area_tow_id = $this->request->post("area_tow_id", 0);

        $where = ['u.status' => 'normal'];
        if ($area_tow_id) {
            $where['v.area_tow_id'] = $area_tow_id;
        }

        $list = $this->vmodel
            ->alias('v')
            ->field('v.*')
            ->where($where)
            ->where(['v.user_id' => $this->auth->id])
            ->where('v.deletetime', null)
            ->join('user u', 'v.user_id = u.id')

            ->order('v.id desc')
            ->select();

        //待審核
        $list2 = db::name('volunteer_audit')->alias('v')
        ->join('area a','a.id=v.affiliated_center_id')
        ->field('a.name as affiliated_center_text,v.area_tow_id')
        ->where(['user_id' => $this->auth->id])->where('status', 1)->select();

        $list = array_merge($list, $list2);

        foreach ($list as $key => &$value) {

            $value['region_address'] = db('area')
                ->where(['id' => $value['area_tow_id']])
                ->value('name');

        }
        unset($value);

        $this->success('請求成功', $list);
    }
    /**
     * @MethodName 獲取關懷任務列表
     * @Author     Allen
     * @DateTime   2021-10-08T10:49:13+0800
     * @param      string
     * @return     [type]
     */
    public function getCaringTaskList($value = '')
    {
        $arrivaltime = $this->request->post("arrivaltime", 0);
        $district    = $this->request->post("district", 0);

        $where = ['c.status' => '1', 'o.status' => '0', 'o.volunteer_id' => $this->volunteer_info['id']];
        if ($arrivaltime) {
            $arrivaltime            = strtotime(date('Y-m-d', $arrivaltime));
            $where['c.arrivaltime'] = ['between', [$arrivaltime, $arrivaltime + 86399]];
        }
        if ($district) {
            $where['c.district'] = $district;
        }
        $total = $this->cmodel
            ->alias('c')
            ->where($where)
            ->join('user u', 'c.user_id = u.id')
            ->join('caring_task_order o', 'o.caring_task_id = c.id')
            ->count();

        $page = new Page($total, 10);
        $list = $this->cmodel
            ->alias('c')
            ->field('c.id,u.nickname,u.avatar,c.province,c.city,c.district,c.address,c.arrivaltime,c.returnvisittime,c.workinghours,c.exp,c.score,c.peoplenum')
            ->where($where)
            ->join('user u', 'c.user_id = u.id')
            ->join('caring_task_order o', 'o.caring_task_id = c.id')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('c.id desc')
            ->select();

        foreach ($list as $key => &$value) {
            $region_address = db('region')
                ->where(['id' => $value['province']])
                ->value('name');

            $city = db('region')
                ->where(['id' => $value['city']])
                ->value('name');

            if ($city) {
                $region_address = $region_address . $city;
                $district       = db('region')
                    ->where(['id' => $value['district']])
                    ->value('name');

                if ($district) {
                    $region_address = $region_address . $district;
                }
            }
            $region_address          = $region_address . $value['address'];
            $value['region_address'] = $region_address ? $region_address : '';
            unset($value['province']);
            unset($value['city']);
            unset($value['district']);
            unset($value['address']);
        }
        unset($value);

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];
        $this->success('請求成功', $data);
    }

    /**
     * @MethodName 領取關懷任務
     * @Author     Allen
     * @DateTime   2021-10-08T11:31:05+0800
     * @param      string
     * @return     [type]
     */
    public function receiveCaringTask($value = '')
    {
        $time     = time();
        $rq_data  = $this->request->param();
        $validate = Loader::validate('VolunteerAudit');
        if (! $validate->scene('task')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $where = ['c.status' => '1', 'o.status' => '0', 'o.volunteer_id' => $this->volunteer_info['id']];
        $info  = $this->cmodel
            ->alias('c')
            ->field('c.id,o.id as order_id,u.nickname,u.avatar,c.province,c.city,c.district,c.address,c.arrivaltime,c.returnvisittime,c.workinghours,c.score,c.peoplenum')
            ->where(['c.id' => $rq_data['id']])
            ->where($where)
            ->join('user u', 'c.user_id = u.id')
            ->join('caring_task_order o', 'o.caring_task_id = c.id')
            ->find();

        if (! $info) {
            $this->error('未找到該任務,請刷新頁面');
        }

        $order_info = db('caring_task_order')
            ->where(['id' => $info->order_id, 'status' => 0, 'volunteer_id' => $this->volunteer_info['id']])
            ->find();

        if (! $order_info) {
            $this->error('未找到該任務,請刷新頁面');
        }

        $status = db('caring_task_order')
            ->where(['id' => $order_info['id']])
            ->update(['status' => '1', 'updatetime' => $time, 'order_receiving_time' => $time]);

        if (! $status) {
            $this->error('操作失敗');
        }

        $this->success('操作成功');

    }

    /**
     * @MethodName 獲取培訓任務列表
     * @Author     Allen
     * @DateTime   2021-10-08T10:49:13+0800
     * @param      string
     * @return     [type]
     */
    public function getTrainingTaskList($value = '')
    {
        $arrivaltime = $this->request->post("arrivaltime", 0);
        $district    = $this->request->post("district", 0);
        $type        = $this->request->post("type", 0);

        $where = ['t.status' => '1', 'o.status' => '0', 'o.volunteer_id' => $this->volunteer_info['id']];
        if ($arrivaltime) {
            $arrivaltime            = strtotime(date('Y-m-d', $arrivaltime));
            $where['t.arrivaltime'] = ['between', [$arrivaltime, $arrivaltime + 86399]];
        }
        if ($district) {
            $where['t.district'] = $district;
        }
        if ($type) {
            $where['t.type'] = $type;
        }
        $total = $this->tmodel
            ->alias('t')
            ->where($where)
            ->join('training_task_order o', 'o.training_task_id = t.id')
            ->count();

        $page = new Page($total, 10);
        $list = $this->tmodel
            ->alias('t')
            ->field('t.id,t.type,t.province,t.city,t.district,t.address,t.arrivaltime,t.workinghours,t.exp,t.score,t.content')
            ->where($where)
            ->join('training_task_order o', 'o.training_task_id = t.id')
            ->limit($page->firstRow . ',' . $page->listRows)
            ->order('t.id desc')
            ->select();

        foreach ($list as $key => &$value) {
            $region_address = db('region')
                ->where(['id' => $value['province']])
                ->value('name');

            $city = db('region')
                ->where(['id' => $value['city']])
                ->value('name');

            if ($city) {
                $region_address = $region_address . $city;
                $district       = db('region')->where(['id' => $value['district']])->value('name');
                if ($district) {
                    $region_address = $region_address . $district;
                }
            }
            $region_address          = $region_address . $value['address'];
            $value['region_address'] = $region_address ? $region_address : '';
            unset($value['province']);
            unset($value['city']);
            unset($value['district']);
            unset($value['address']);
        }
        unset($value);

        $data = ['total' => $total, 'listrows' => $page->listRows, 'totalpages' => $page->totalPages, 'data' => $list];
        $this->success('請求成功', $data);
    }

    /**
     * @MethodName 領取培訓任務
     * @Author     Allen
     * @DateTime   2021-10-08T11:31:05+0800
     * @param      string
     * @return     [type]
     */
    public function receiveTrainingTask($value = '')
    {
        $time     = time();
        $rq_data  = $this->request->param();
        $validate = Loader::validate('VolunteerAudit');
        if (! $validate->scene('task')->check($rq_data)) {
            $this->error($validate->getError());
        }

        $where = ['t.status' => '1', 'o.status' => '0', 'o.volunteer_id' => $this->volunteer_info['id']];
        $info  = $this->tmodel
            ->alias('t')
            ->field('t.id,o.id as order_id,t.type,t.province,t.city,t.district,t.address,t.arrivaltime,t.workinghours,t.score,t.content')
            ->where(['t.id' => $rq_data['id']])
            ->where($where)
            ->join('training_task_order o', 'o.training_task_id = t.id')
            ->find();

        if (! $info) {
            $this->error('未找到該任務,請刷新頁面');
        }
        $order_info = db('training_task_order')
            ->where(['id' => $info->order_id, 'status' => 0, 'volunteer_id' => $this->volunteer_info['id']])
            ->find();

        if (! $order_info) {
            $this->error('未找到該任務,請刷新頁面');
        }

        $status = db('training_task_order')
            ->where(['id' => $order_info['id']])
            ->update(['status' => '1', 'updatetime' => $time, 'order_receiving_time' => $time]);

        if (! $status) {
            $this->error('操作失敗');
        }

        $this->success('操作成功');
    }

}
